package com.tinyideatech.admin.controller.system;

import com.tinyideatech.common.core.controller.BaseController;
import com.tinyideatech.common.core.entity.ApiResult;
import com.tinyideatech.common.utils.StringUtils;
import com.tinyideatech.framework.cache.CacheConst;
import com.tinyideatech.framework.utils.DigestsUtils;
import com.tinyideatech.system.entity.SysUser;
import com.tinyideatech.system.service.IMallMemberService;
import org.apache.commons.codec.binary.Hex;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
public class SysLoginController extends BaseController {

    @Autowired
    private IMallMemberService memberService;

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @ResponseBody
    @GetMapping("/pwd")
    public String pwd(
            @RequestParam(required = false, defaultValue = "") String pwd
    ) {
        byte[] password = DigestsUtils.sha1(pwd.getBytes(), 1024);
        return new String(Hex.encodeHex(password));
    }

    @GetMapping("/login")
    public String login(
    ) {
        return "login";
    }

    @GetMapping("/register")
    public String register(
    ) {
        return "register";
    }

    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public ApiResult loginUser(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam(required = false, defaultValue = "/index") String callBackUrl,
            HttpSession session
    ){
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, true);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            SysUser user = (SysUser) subject.getPrincipal();
            session.setAttribute(CacheConst.CURRENT_USER, user);
//            session.setAttribute("user_info", memberService.getById(1177238092613033986L));
//            session.setAttribute("user_id", 1177238092613033986L);
//            session.setAttribute("device_id", "sks3197uiop09177");
            return success();
        } catch (Exception e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

}
